package edu.msu.scrabble.project1;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class GlobalMenuActivity extends Activity {

	protected Cloud thecloud = null;
	protected GlobalMenuActivity instance = this;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_global_menu);
		
		thecloud = Cloud.get();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_global_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		
		final ContextWrapper activity = this;
		final Handler mainHandler = new Handler(this.getMainLooper());
		
		switch(item.getItemId()) {
		case R.id.menu_log_out:
			new Thread(new Runnable() {
	        	
	            @Override
	            public void run() {
	            	final boolean loggedout = thecloud.logOut();
	            	
	            	mainHandler.post(new Runnable() {
	            		/*
	            		 * If the user was logged in then we can send them to the next activity
	            		 */
	            		@Override
	    	            public void run() {
	            			if (loggedout){
	            				Toast.makeText(activity, R.string.logout_succeeded, Toast.LENGTH_SHORT).show();
	            				
	            				Intent intent = new Intent(activity, LogInActivity.class);
	            				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
	            				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	            				startActivity(intent);
	            				finish();
	    	            	}
	    	                else
	    	                {
	    	                	// This shouldn't ever happen
	    	                	Toast.makeText(activity, R.string.logout_failed, Toast.LENGTH_SHORT).show();
	    	                }
	                    }
	            	});
	            }
	        }).start();
			
			break;
		}
		return true;
	}

	/*
	 * Make sure our session is set up, bounce to log in otherwise
	 */
	@Override
	protected void onResume() {
		super.onResume();
		
		if(!thecloud.loggedIn()) {
			Toast.makeText(this, R.string.text_not_loggedin, Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(this, LogInActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		}
	}
	
	
	 @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		if(thecloud.isNotLeavingApp() || thecloud.isEndGameFlag()) {
			// If we aren't leaving the app then we don't want to log out the user
		}
		else {
			// We are leaving the app so log out
			Thread thread = new Thread(new Runnable() {
	   			
	   			@Override
	   			public void run(){		           			
	   				thecloud.logOut();
	   				Intent intent = new Intent(instance , LogInActivity.class);
	   				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
	   				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	   				startActivity(intent);
	   				
	   			}
	   	
	   		
	   			});
	   			thread.start();
		}
		if(thecloud.isNotLeavingApp())
			thecloud.setNotLeavingApp(false);
		if(thecloud.isEndGameFlag())
			thecloud.setEndGameFlag(false);
	}

	@Override
	    public boolean onKeyDown(int keyCode, KeyEvent event) 
	    {
	        if (keyCode == KeyEvent.KEYCODE_BACK)
	        {
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
	 
				// set title
				alertDialogBuilder.setTitle(R.string.quit);

		        alertDialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
		               @Override
		               public void onClick(DialogInterface dialog, int id) {
		            	   Thread thread = new Thread(new Runnable() {
		           			
		           			@Override
		           			public void run(){		           			
		           				thecloud.logOut();
		           				Intent intent = new Intent(instance , LogInActivity.class);
		           				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
		           				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		           				startActivity(intent);
		           				
		           			}
		           	
		           		
		           			});
		           			thread.start();	
		            	       }
		        })
		        
	           .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	                   
	               }
	           });
		        
		        // Create the dialog box and show it
		        AlertDialog alertDialog = alertDialogBuilder.create();
		        alertDialog.show();
			}

	        return true;
	    }
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	    super.onConfigurationChanged(newConfig);

	    // Checks the orientation of the screen
	    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE || newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
	    	thecloud.setNotLeavingApp(true);
	    	onPause();
	    }
	}
	
//	/**
//     * Handle a saveInstanceState
//     */
//	@Override
//	protected void onSaveInstanceState(Bundle outState) {
//		super.onSaveInstanceState(outState);
//		thecloud.setNotLeavingApp(true);
//	}
	
}
